package com.guaju.yueshangLife.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 应用程序Activity管理类：用于Activity管理和应用程序退出
 *
 * @author lucl-a
 * @version 1.0
 * @created 2014-12-18
 */
public class AppManager {

    public static ConcurrentHashMap<Class<?>,Activity> activityStack = new ConcurrentHashMap<Class<?>,Activity>();
    private static AppManager		instance;

    private AppManager() {
    }

    /**
     * 单一实例
     */
    public static synchronized AppManager getAppManager() {
        if (instance == null) {
            synchronized (AppManager.class) {
                if (instance == null)
                    instance = new AppManager();
            }
        }
        return instance;
    }

    /**
     * 添加Activity到堆栈
     */
    public void addActivity(Activity activity) {
        if (activityStack.containsKey(activity.getClass())) {
            Activity activityInstance = activityStack.get(activity.getClass());
            activityStack.remove(activity.getClass());
            mActivityDeque.remove(activityInstance);
        }
        activityStack.put(activity.getClass(), activity);
        mActivityDeque.addLast(activity);
    }

    /**
     * 获取指定类名的Activity
     */

    public static Activity getActivity(Class<?> cls) {
        for (Activity activity : activityStack.values()) {
            if (activity.getClass().equals(cls)) {
                return activity;
            }
        }
        return null;
    }

    /**
     * 结束指定的Activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null) {
            if (activityStack.contains(activity)) {
                Activity activityInstance = activityStack.get(activity.getClass());
                activityStack.remove(activity.getClass());
                mActivityDeque.remove(activityInstance);
                activity.finish();
                activity = null;
            }
        }
    }

    /**
     * 结束指定类名的Activity
     */
    public void finishActivity(Class<?> cls) {
        for (Activity activity : activityStack.values()) {
            if (activity.getClass().equals(cls)) {
                finishActivity(activity);
                break;
            }
        }
    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        Iterator iter = activityStack.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            Object value = entry.getValue();
            Activity activity = (Activity)value;
            activity.finish();
            activity = null;
        }
//        MeFragment.setIsChooseAvater(false);
        activityStack.clear();
        mActivityDeque.clear();
    }

    /**
     * 结束掉除了指定activity和主界面的所有activity
     */
    public synchronized void finishActivitys(Class<?> cls) {
        ArrayList<Activity> list = new ArrayList<Activity>();
        for (Activity activity : activityStack.values()) {
            if (!activity.getClass().equals(cls)) {
                list.add(activity);
            }
        }
        for (Activity activity : list) {
            finishActivity(activity);
        }
    }

    /**
     * 结束掉除了指定activity的所有activity
     */
    public synchronized void finishAllActivitys(Class<?> cls) {
        ArrayList<Activity> list = new ArrayList<Activity>();
        for (Activity activity : activityStack.values()) {
            if (!activity.getClass().equals(cls)) {
                list.add(activity);
            }
        }
        for (Activity activity : list) {
            finishActivity(activity);
        }
    }

    /**
     * 退出应用程序
     */
    public void AppExit(Context context) {
        try {
            finishAllActivity();
            int currentVersion = android.os.Build.VERSION.SDK_INT;
            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            if (currentVersion > android.os.Build.VERSION_CODES.ECLAIR_MR1) {
                Intent startMain = new Intent(Intent.ACTION_MAIN);
                startMain.addCategory(Intent.CATEGORY_HOME);
                startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                context.startActivity(startMain);
                activityManager.killBackgroundProcesses(context.getPackageName());
            } else {
                // android2.1 支持 restartPackage 结束
                activityManager.restartPackage(context.getPackageName());
            }
//            Session.onKillProcess();
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(0);
        }
        catch (Exception e) {}
    }


    /** 双端队列 **/
    public static LinkedList<Activity> mActivityDeque = new LinkedList<Activity>();

    public Activity getLastActivity() {
        if (mActivityDeque == null || mActivityDeque.isEmpty()) {
            return null;
        }
        return mActivityDeque.getLast();
    }

}